<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
          v-model="state.listQuery.keyword"
          style="width: 200px"
          class="filter-item"
          @keyup.enter="handleList"
      />
      <el-button
          v-waves
          class="filter-item"
          type="primary"
          @click="handleList"
          clearable
      >
        <el-icon style="vertical-align: middle">
          <Search/>
        </el-icon>
        搜索
      </el-button>
      <el-button
          class="filter-item"
          style="margin-left: 10px"
          type="primary"
          @click="handleCreate"
      >
        <el-icon style="vertical-align: middle">
          <Edit/>
        </el-icon>
        添加
      </el-button>
      <el-button
          v-waves
          :loading="downloadLoading"
          class="filter-item"
          type="primary"
          @click="handleDownload"
      >
        <el-icon style="vertical-align: middle">
          <Download/>
        </el-icon>
        导出
      </el-button>
    </div>
    <el-table
        v-loading="state.listLoading"
        :data="state.list"
        :load="state.listLoading"
        border
        style="width: 100%">
      <el-table-column
          label="ID"
          prop="id"
          align="center"
          width="60">
      </el-table-column>
      <el-table-column
          label="用户名"
          prop="username"
          align="center"
          width="140">
      </el-table-column>
      <el-table-column
          label="昵称"
          prop="nickName"
          align="center"
          width="150">
      </el-table-column>
      <el-table-column
          label="角色"
          prop="roles"
          align="center"
          width="350">
        <template #default="scope">
          <el-tag
              class="role-tag"
              size="small"
              v-if="scope.row.roles != null"
              v-for="item in scope.row.roles.split(',')"
          ><span v-text="item"/></el-tag>
        </template>
      </el-table-column>
      <el-table-column
          label="邮箱"
          prop="email"
          align="center"
          width="170">
      </el-table-column>
      <el-table-column
          label="添加时间"
          prop="createTime"
          align="center"
          width="160">
        <template #default="scope">
          <span v-text="formatDateTime(scope.row.createTime)"/>
        </template>
      </el-table-column>
      <el-table-column
          label="最后登录"
          prop="loginTime"
          align="center"
          width="160">
        <template #default="scope">
          <span v-text="formatDateTime(scope.row.loginTime)"/>
        </template>
      </el-table-column>
      <el-table-column
          label="是否启用"
          prop="status"
          width="90"
          align="center">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              @change="changeStatus(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleAssignRole(scope.row)"
          >分配角色
          </el-button>
          <el-button size="small" @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <el-popconfirm title="确认删除?"
                         @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button
                  size="small"
                  type="danger"
              >删除
              </el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm/>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top:10px">
      <el-pagination
          :total="state.total"
          v-model:page="state.listQuery.pageNum"
          v-model:limit="state.listQuery.pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="state.listQuery.pageNum"
          :page-sizes="[10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
    <el-dialog
        :title="state.textMap[state.dialogStatus]"
        v-model="state.dialogFormVisible"
    >
      <el-form
          ref="dataForm"
          :rules="state.rules"
          :model="state.defaultAdminModel"
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left: 50px"
      >
        <el-form-item
            label="用户名"
            prop="username"
        >
          <el-input v-model="state.defaultAdminModel.username"
                    maxlength="30"
                    show-word-limit/>
        </el-form-item>
        <el-form-item
            label="密码"
            prop="password"
            v-if="state.dialogStatus === 'create'"
        >
          <el-input v-model="state.defaultAdminModel.password"
                    maxlength="18"
                    show-word-limit/>
        </el-form-item>
        <el-form-item
            label="昵称"
            prop="nickName"
        >
          <el-input v-model="state.defaultAdminModel.nickName"
                    maxlength="30"
                    show-word-limit/>
        </el-form-item>
        <el-form-item
            label="状态"
            prop="status"
        >
          <el-switch v-model="state.defaultAdminModel.status"/>
        </el-form-item>
        <el-form-item
            label="头像"
            prop="icon"
        >
          <el-upload
              class="avatar-uploader"
              :action="actionUrl"
              :auto-upload=true
              :on-remove="handleRemove"
              :on-change="handleChange"
              :before-upload="handleBeforeUpload"
          >
            <img v-if="state.defaultAdminModel.icon" :src="state.defaultAdminModel.icon" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item
            label="邮箱"
            prop="email"
        >
          <el-input type="email" v-model="state.defaultAdminModel.email"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="state.defaultAdminModel.note"
              :autosize="{minRows: 2, maxRows: 5}"
              type="textarea"
              placeholder="请输入..."
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="state.dialogFormVisible = false">
          取消
        </el-button>
        <el-button
            type="primary"
            @click="state.dialogStatus === 'create' ? createData() : updateData()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
        title="分配角色"
        v-model="state.dialogAssignRoleFormVisible"
        style="width: 500px"
    >
      <el-form
          ref="dataForm"
          label-position="left"
          label-width="100px"
          style="width: 500px; margin-left: 20px; margin-bottom: 100px"
      >
        <el-select
            placeholder="请选择角色"
            v-model="state.selectRoles"
            multiple
            filterable
            style="width: 80%"
        >
          <el-option v-for="item in state.allRole"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
          <slot/>
        </el-select>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="state.dialogAssignRoleFormVisible = false">
          取消
        </el-button>
        <el-button
            type="primary"
            @click="assignRoles()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  reactive,
  onMounted,
  ref
} from 'vue'
import {get, post, put, del, handleRegexpTxt, postFile} from '@/utils/http'
import {ElForm, ElMessage} from 'element-plus'
import {apis} from '@/apis'
import moment from 'moment'
import {cloneDeep} from 'lodash'
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const dataForm = ref(ElForm)
const actionUrl = ref(apis.UPLOAD_FILE)
const adminModel = {
  id: null,
  nickName: '',
  password: '',
  status: true,
  icon: '',
  email: '',
  nickname: '',
  note: ''
}
const state = reactive({
  tableKey: 0,
  list: [],
  total: 0,
  listLoading: true,
  listQuery: {
    pageNum: 1,
    pageSize: 10,
    keyword: undefined
  },
  dialogFormVisible: false,
  dialogAssignRoleFormVisible: false,
  textMap: {
    update: '编辑管理员',
    create: '添加管理员'
  },
  dialogStatus: '',
  rules: {
    username: [
      {required: true, message: '请输入用户名', trigger: 'change'}
    ],
    nickName: [
      {required: true, message: '请输入昵称', trigger: 'change'},

    ],
    password: [
      {required: true, message: '请输入密码', trigger: 'change'},
      {min: 6, max: 18, message: '密码长度需要在6到18位', trigger: 'change'}
    ]
  },
  defaultAdminModel: adminModel,
  allRole: [],
  selectRoles: [],
  adminId: null
})


const handleList = () => {
  state.listLoading = true
  get(apis.UMS_ADMIN, {params: state.listQuery}).then((res) => {
    console.log(res)
    state.list = res.data
    state.total = res.page.total
    state.listQuery.pageNum = res.page.current
    state.listQuery.pageSize = res.page.size
    state.listLoading = false
  })
}

const getAllRole = () => {
  get(apis.ALL_ROLE).then((res) => {
    state.allRole = res.data
  })
}

const changeStatus = (row) => {
  let activateUmsAdmin = handleRegexpTxt(apis.ACTIVATE_UMS_ADMIN, '{id}', row.id);
  let suspendedUmsAdmin = handleRegexpTxt(apis.SUSPENDED_UMS_ADMIN, '{id}', row.id);
  console.log(row.status)
  if (row.status) {
    put(activateUmsAdmin)
  } else {
    put(suspendedUmsAdmin)
  }
}
const resetAdminModel = () => {
  state.defaultAdminModel = cloneDeep(adminModel)
}

const handleCreate = () => {
  resetAdminModel()
  state.dialogStatus = 'create'
  state.dialogFormVisible = true
}

const handleUpdate = (row) => {
  resetAdminModel()
  state.dialogStatus = 'update'
  state.dialogFormVisible = true
  state.defaultAdminModel = row
}

const handleDelete = (row) => {
  let oneUmsAdmin = handleRegexpTxt(apis.ONE_UMS_ADMIN, '{id}', row.id);
  del(oneUmsAdmin).then((res) => {
    handleList()
  })
}

const createData = () => {
  const form = ref(dataForm)
  form.value.validate(async (valid) => {
    if (valid) {
      post(apis.UMS_ADMIN, state.defaultAdminModel).then((res) => {
        state.dialogFormVisible = false
        handleList()
      })
    }
  })
}

const updateData = () => {
  const form = ref(dataForm)
  let oneUmsAdmin = handleRegexpTxt(apis.ONE_UMS_ADMIN, '{id}', state.defaultAdminModel.id);
  form.value.validate(async (valid) => {
    if (valid) {
      put(oneUmsAdmin, state.defaultAdminModel).then((res) => {
        state.dialogFormVisible = false
        handleList()
      })
    }
  })
}

const handleAssignRole = (row) => {
  state.dialogAssignRoleFormVisible = true
  state.adminId = row.id
  state.selectRoles = []
  let adminRoles = handleRegexpTxt(apis.ADMIN_ROLES, '{adminId}', row.id);
  get(adminRoles).then((res) => {
    if (res.data != null) {
      for (let i of res.data) {
        state.selectRoles.push(i.id)
      }
    }
  })
}

const assignRoles = () => {
  console.log(state.selectRoles)
  let assignRoles = handleRegexpTxt(apis.ASSIGN_ROLES, '{id}', state.adminId);
  post(assignRoles, {"roles": state.selectRoles}).then((res) => {
    state.adminId = null
    state.dialogAssignRoleFormVisible = false
    handleList()
  })
}

const formatDateTime = (value) => {
  if (value === null) {
    return value
  }
  return moment(value).format('YYYY-MM-DD HH:mm:ss');
}

const handleSizeChange = (val) => {
  state.listQuery.pageSize = val
  handleList()
}

const handleCurrentChange = (val) => {
  state.listQuery.pageNum = val
  handleList()
}

const handleChange = (file) => {
  if (!(file.raw.type === 'image/png' || file.raw.type === 'image/jpg' || file.raw.type === 'image/jpeg')) {
    ElMessage({
      showClose: true,
      message: '请上传格式为image/png, image/jpg, image/jpeg的图片',
      type: 'warning',
      duration: 3000
    })
    return false
  }
  let size = file.size / 1024 / 1024
  if (size > 20) {
    ElMessage({
      showClose: true,
      message: '图片大小必须小于20M',
      type: 'warning',
      duration: 3000
    })
    return false
  }
  return true
}

const handleBeforeUpload = (file) => {
  postFile(apis.UPLOAD_FILE, file).then((res) => {
    state.defaultAdminModel.icon = res.data
    console.log(res.data)
  })
  return false
}

const handleRemove = (file) => {
  
}

onMounted(() => {
  handleList()
  getAllRole()
})

</script>

<style>
.role-tag {
  margin-right: 2px;
}
.avatar-uploader .avatar {
  width: auto;
  height: auto;
  max-width: 90%;
  max-height: 90%;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
</style>


